import { getRecordsByUser } from '../../../apis/order'
import { getUID } from '../../../utils/permission'

Page({
  data: {
    pageStatus: 'loading', // error, done
    orders: [],
    loadMoreStatus: 'hidding' // loading, nomore
  },

  /**
   * @listens <orderDeleted>
   */
  onLoad: function () {
    // 监听事件
    getApp().event.on('orderDeleted', this.onOrderDeleted)
    this._loadPage()
  },

  onReloadPage: function () {
    this._loadPage()
  },

  onReachBottom: function () {
    const { loadMoreStatus, orders } = this.data
    if (loadMoreStatus !== 'hidding') return

    this.setData({loadMoreStatus: 'loading'})
    getRecordsByUser(getUID(), orders.length).then(res => {
      this.setData({
        orders: orders.concat(res.data.list),
        loadMoreStatus: res.data.list.hasNextPage ? 'hidding' : 'nomore'
      })
    }).catch(() => this.setData({loadMoreStatus: 'hidding'}))
  },



  _loadPage: function () {
    this.setData({pageStatus: 'loading'})
    getRecordsByUser(getUID()).then(res => {
      this.setData({
        pageStatus: 'done',
        orders: res.data.list
      })
    }).catch(() => this.setData({pageStatus: 'error'}))
  }
})
